package top.maof.book.spider.develop.contents.sangwu;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import top.maof.book.model.Book;
import top.maof.book.model.Contents;
import top.maof.book.spider.develop.Split;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.model.AfterExtractor;
import us.codecraft.webmagic.model.annotation.ExtractBy;
import us.codecraft.webmagic.model.annotation.HelpUrl;
import us.codecraft.webmagic.model.annotation.TargetUrl;

import java.util.Date;

@TargetUrl("http://www.sangwu8.com/book/\\d+/\\d+/")
@HelpUrl({"http://www.sangwu8.com/class/\\d+_\\d+.htm", "http://www.sangwu8.com/paihang/"})
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Sangwu implements AfterExtractor, Split {

    @ExtractBy(value = "//div[@class=intro]/div[@class=introcent]/div[@class=introcents]/h2/text()")
    private String name;

    @ExtractBy(value = "//div[@class=intro]/div[@class=introcent]/p[2]/text()")//作者：我家两只喵
    private String author;

    @ExtractBy(value = "//div[@class=intro]/div[@class=introleft]/img/@src")
    private String img;

    @ExtractBy(value = "//div[@class=src]/div[@class=left]/a[2]/text()")
    private String classify;//科幻小说

    private Date updateDate;

    private Date insertDate = new Date();

    @ExtractBy(value = "//div[@class=intro]/div[@class=introcent]/p[4]/text()")
    private String synopsis;

    private String state;

    private String url;

    private String content;

    private Integer webId = 7;

    public static final String CHARSET = "gbk";

    @Override
    public void afterProcess(Page page) {

        this.author = this.author.substring(3, this.author.length());
        this.name = this.name.trim();

        //img字段做处理  /fengmian/1/1065/1065s.jpg
        if (!this.img.startsWith("http")) {
            if (this.img.startsWith("/"))
                //绝对地址
                this.img = "http://www.sangwu8.com" + this.img;
            else {
                //相对地址
                this.img = page.getUrl().toString().substring(0, page.getUrl().toString().lastIndexOf("/") + 1) + this.img;
            }
        }
        //获取该页面url
        this.setUrl(page.getRequest().getUrl());
    }

    @Override
    public Book getBook() {
        Book book = new Book();
        book.setName(this.name);
        book.setAuthor(this.author);
//        book.setState(this.state);
//        book.setImg(this.img);
//        book.setInsertDate(this.insertDate);
//        book.setClassify(this.classify);
//        book.setSynopsis(this.synopsis);
//        book.setUpdateDate(this.updateDate);
        return book;
    }

    @Override
    public Contents getContents() {
        Contents contents = new Contents();
        contents.setUrl(this.url);
        contents.setContent(this.content);
        contents.setWebId(this.webId);
        contents.setUpdateDate(this.updateDate);
        return contents;
    }
}